package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.LOGIN_CODE_KEY;
import static com.hmdp.utils.RedisConstants.LOGIN_CODE_TTL;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result sendCode(String phone, HttpSession session) {
        //1.校验手机号
        boolean phoneInvalid = RegexUtils.isPhoneInvalid(phone);
        //2如果不符合手机号标准，返回错误信息
        if(phoneInvalid) {
            return Result.fail("手机号格式错误");
        }
        //3.符合，生成验证码
        String s = RandomUtil.randomNumbers(6);
//        //4.保存验证码到session
//        session.setAttribute("code",s);
        //4.保存到redis中
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY+phone,s,LOGIN_CODE_TTL, TimeUnit.MINUTES); // 60秒过期
        //5.发送验证码
        log.debug("发送验证码成功，验证码：{}",s);
        return Result.ok();
    }

    @Override
    public Result userLogin(LoginFormDTO loginForm, HttpSession session) {
        //1.校验手机号
        boolean phoneInvalid = RegexUtils.isPhoneInvalid(loginForm.getPhone());
        if(phoneInvalid) {
            return Result.fail("手机号格式错误");
        }
        //2.校验验证码
        String code = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY + loginForm.getPhone());
        if(code == null || !code.equals(loginForm.getCode())) {
            //3.不一致 报错
            return Result.fail("验证码错误");
        }
        //4.一致的话 根据手机号查询用户
        User user = query().eq("phone", loginForm.getPhone()).one();
        //5.不存在 创建新用户保存数据库
        if(user == null) {
            user = new User();
            user.setPhone(loginForm.getPhone());
            user.setNickName(SystemConstants.USER_NICK_NAME_PREFIX + RandomUtil.randomString(10));
            save(user);
        }
//        //6.保存用户信息到session并返回结果
//        //6.1将用户数据转换为UserDTO
//        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
//        session.setAttribute("user",userDTO);

        //6.保存用户信息到redis中
        //6.1.随机生成token，作为登录令牌
        String token = UUID.randomUUID().toString(true);
        //6.2.将User对象转为HashMap存储
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        Map<String, Object> stringObjectMap = BeanUtil.beanToMap(userDTO
        ,new HashMap<>(), CopyOptions.create()
                        .setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldName,fieldValue)->
                        fieldValue.toString()));
        //6.3.存储
        String tokenKey= RedisConstants.LOGIN_USER_KEY+token;
        stringRedisTemplate.opsForHash().putAll(tokenKey,stringObjectMap);
        //6.4.设置token有效期
        stringRedisTemplate.expire(tokenKey,RedisConstants.LOGIN_USER_TTL,TimeUnit.MINUTES);

        return Result.ok(token);
    }

    @Override
    public Result logout(HttpSession session) {
        session.removeAttribute("user"); // 移除session
        return Result.ok();
    }

    @Override
    public Result sign() {
        //1.获取用户信息
        Long userId = UserHolder.getUser().getId();
        //2.获取日期
        LocalDateTime now = LocalDateTime.now();
        String date = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        //3.拼接key
        String key = RedisConstants.USER_SIGN_KEY + userId + date;
        //4.获取今天为第几天
        int dayOfMonth = now.getDayOfMonth();
        //5.写入redis
        stringRedisTemplate.opsForValue().setBit(key,dayOfMonth-1,true);
        //返回
        return Result.ok();
    }

    /**
     *签到统计
     * @return
     */
    @Override
    public Result signCount() {
        //1.获取用户信息
        Long userId = UserHolder.getUser().getId();
        //2.获取日期
        LocalDateTime now = LocalDateTime.now();
        String date = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        //3.拼接key
        String key = RedisConstants.USER_SIGN_KEY + userId + date;
        //4.获取今天为第几天
        int dayOfMonth = now.getDayOfMonth();
        //5.获取本月截止到的所有签到记录，返回的是一个十进制的数字 BITFIELD sign:5:202203 GET u14 0
        List<Long> longs = stringRedisTemplate.opsForValue().bitField(
                key,
                BitFieldSubCommands.create().get(
                                BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth))
                        .valueAt(0));
        if(longs == null || longs.isEmpty()) {
            //没有任何签到记录，返回0
            return Result.ok(0);
        }

        Long result = longs.get(0);
        if(result == null|| result == 0) {
            return Result.ok(0);
        }
        //6.循环遍历
        int dayCount = 0;
        while (true) {
            if( (result & 1) == 0) {
                //0 表示未签到
                break;
            }else {
                //1 表示已签到
                dayCount++;
            }
            //result右移1位
            result >>>= 1;
        }
        //7.返回结果
        return Result.ok(dayCount);
    }

}
